<?php

/**
 * 充值_控制器
 * @property Recharge_order_mdl $rechargeOrder
 * @property Rechargecard_mdl $rechargecard
 * @property WxPayApi $wxApi
 */
class Recharge extends MY_Controller {
	/**
	 */
	public function __construct() {
		parent::__construct ();
		$this->user = parent::getLoginUser();
		$this->load->model('Recharge_order_mdl','rechargeOrder');
		$this->load->library('wxApi/wxPayApi',NULL,'wxApi');
		$this->wxApi->setConfigGroup('yx');
	}
	/**
	 * 创建微信预支付订单
	 * 	传入参数:充值金额(单位:分)
	 * 	返回参数:微信预支付参数(prepay_id,sign等)
	 */
	public function wx_prepay(){
		$time = time();
		// ----获取充值金额---
		$amount = isset($_REQUEST['amount']) ? (int)$_REQUEST['amount'] : 0;
		if ( $amount<=0 ) {
			$this->apiOutput->errorInput();
		}
		// ----创建商户订单号----
		// 	10位时间戳(精确到秒)+8位用户ID
		// 	微信要求：不超过32位,可含字母
		//  在数据库中,tradeID字段被定义为20位的UNSIGNED BIGINT ,唯一键
		$tradeID = time().sprintf('%08s',$this->user->id);
		// ----调用微信下单接口----
		$result = $this->wxApi->setParams('body','荣钧健康饮水-充值')
							->setParams('notify_url','http://heshui-api.yxlady.com/callback/wx_pay')
							->setParams('out_trade_no',$tradeID)
							->setParams('total_fee',$amount)
							->setParams('trade_type','APP')
// 							->setParams('appid','wx5fa33440277208bf')
// 							->setParams('mch_id','1400250502')
							->unifiedorder();
		if( ! $result ){
			$this->apiOutput->errorSystem();
		}
		
		// 插入充值订单表
		$insert = array();
		$insert['userID'] = $this->user->id;
		$insert['amount'] = $amount;
		$insert['payTime']   = $time;
		$insert['tradeState'] = 'PREPAY';
		$insert['tradeID']= $tradeID;
		$insert['wxPrepayID'] = $result['prepayID'];
		$insert['wxTradeType'] = 'APP';
		$orderID = $this->rechargeOrder->addPrepayOrder($insert);
		
		if ( !$orderID ) {
			$this->apiOutput->errorSystem();
		}
		$this->apiOutput->put('tradeID', $orderID)
						->put('data', $result['appData'])
						->out();		
	}
	/**
	 * 查询实际支付结果
	 * 	传入参数:
	 * 		tradeID:订单ID
	 */
	public function wx_order_query(){
		$orderID = (int)$this->input->post_get('tradeID',TRUE);
		if( empty($orderID) ){
			$this->apiOutput->errorInput();
		}
		$order = $this->rechargeOrder->queryOrderResult($orderID);
		debug('order',$order);
		$tradeState = strtoupper($order['tradeState']);
		$tradeStatesCN = array(
			'SUCCESS'=>'支付成功',
			'PREPAY'=>'待支付',
			'NOTPAY'=>'未支付',
			'REFUND'=>'转入退款',
			'CLOSED'=>'已关闭',
			'REVOKED'=>'已撤销',
			'USERPAYING'=>'用户支付中',
			'PAYERROR'=>'支付失败',
		);
		$msg = isset($tradeStatesCN[ $tradeState ]) ? $tradeStatesCN[ $tradeState ] : '支付失败';
		$amount = (int)$order['amount'];
		$this->apiOutput->put('tradeState',$tradeState)
						->put('msg',$msg)
						->put('amount',$amount)
						->put('balance',(int)$this->user->balance)
						->out();
	}
	
	/**
	 * 充值记录
	 */
	public function log(){
		$input = &$_REQUEST;
		$bottomID = isset($input['bottomID']) ? (int)$input['bottomID'] : 0 ;
		$count    = isset($input['count']) ? (int)$input['count'] : 20;
		$count    = $count>0 ? $count : 20;
		$tradeState = isset($input['tradeState']) ? strtoupper($input['tradeState']) : 'SUCCESS';
		$where = array();
		$where['userID'] = $this->user->id;
		if( $bottomID > 0 ){
			$where['id < '] = $bottomID;
		}
		if( 'ALL' != $tradeState ){
			$where['tradeState'] = $tradeState;
		}
		$select = 'id,amount,payTime,tradeState,isAdded,wxTradeType';
		$order  = 'id';
		$sort   = 'DESC';
		$list = $this->rechargeOrder->getList($select,$where,$count+1,0,$order,$sort);
		$hasMore = 0;
		if( count($list) > $count ){
			$hasMore = 1;
			array_pop($list);
		}
		$list = array_map(function($v){
			if($v['wxTradeType']=='CARD'){
				$v['desc'] = '充值卡充值成功';
			}else{
				$v['desc'] = $v['isAdded'] ? '充值成功' : '等待确认' ;
			}
			unset($v['wxTradeType']);
			unset($v['isAdded']);
			return $v;
		}, $list);
		$this->apiOutput->put('hasMore',$hasMore)->put('balance', $this->user->balance)->put('list', $list)->out();
	}
	
	/**
	 * 充值卡充值
	 */
	public function card(){
		// 输入检查
		$num = $this->input->post_get ( 'num' ,TRUE);
		$pwd = $this->input->post_get ( 'pwd' ,TRUE);
		if (empty ( $num ) || empty ( $pwd )) {
			$this->apiOutput->errorInput ();
		}
		$this->load->model ( 'Rechargecard_mdl', 'rechargecard' );
		// 检查该卡是否可用
		$where = array (
				'id' => $num,
				'cardpwd' => $pwd 
		);
		$card = $this->rechargecard->getOne ( $where );
		if (empty ( $card )) {
			$this->apiOutput->error ( '该卡号不存在或密码错误', - 1 );
		}
		if ($card ['userID'] != 0) {
			$this->apiOutput->error ( '该卡已充值过!', - 2 );
		}
		// 检查排他锁
		$lock = $this->rechargecard->getCardLock($card['id']);
		$this->rechargeCardLock = $lock;
		if( $lock->isLock() ){
			$lock->unlock();
			$this->apiOutput->error('系统繁忙,请稍后再试!',-3);
		}
		// 更新卡信息为已消费
		$update = array (
				'userID' => $this->user->id,
				'useTime' => time () 
		);
		$res = $this->rechargecard->update ( $where, $update );
		// 为该用户充值
		if ($res) {
			$amount = $card ['amount'];
			$res = $this->user->rechargeByCard ( $amount );
		}
		// 记录到充值表
		if( $res ){
			$log = array(
					'userID' => $this->user->id,
					'amount' => $card ['amount'],
					'tradeState' => 'SUCCESS',
					'tradeID' => $card ['id'],
					'wxTradeType' => 'CARD',
					'payTime' => time (),
					'isAdded' => 1,
			);
			$res = $this->rechargeOrder->insert($log);
		}
		// 解锁
		$lock->unlock();
		if (! $res) {
			$this->apiOutput->errorSystem ();
		}
		// 返回用户最新余额
		$this->apiOutput
				->put ( 'balance', $this->user->balance )
				->put('cardAmount',$amount)
				->out ();
	}
	
	public function __destruct(){
		// 如果有充值卡排它锁:解锁
		if(!empty($this->rechargeCardLock)){
			$this->rechargeCardLock->unlock();
		}
	}
	
	
	
	
	
	
	
	
	
}

